package org.example.commond.handler;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.commond.AbstractCmdHandler;
import org.example.config.Chat;
import org.example.config.Im;
import org.example.config.ImConfig;
import org.example.enums.CommandEnum;
import org.example.packets.Status;
import org.example.packets.bean.Auth;
import org.example.packets.bean.Group;
import org.example.packets.bean.User;
import org.example.packets.handler.system.LoginRespBody;
import org.example.packets.handler.system.RespBody;
import org.example.packets.handler.user.GroupUser;
import org.example.packets.handler.user.UserStatusBody;
import org.example.util.JsonUtil;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.intf.Packet;
import org.tio.websocket.common.WsResponse;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
public class LoginReqHandler extends AbstractCmdHandler {

    @Override
    public CommandEnum command() {
        return CommandEnum.COMMAND_LOGIN_REQ;
    }

    @Override
    public WsResponse handler(Packet packet, ChannelContext channelContext) {

        String token = JsonUtil.packetBody(packet);

        JWT jwt = JWTUtil.parseToken(token);
        String uid = (String) jwt.getPayload("uid");

        Auth auth = authService.getByUserId(uid);

        // 持久化获取用户信息
        User user = ImConfig.userListener().onGetUser(auth.getUserId());

        // 获取持久化用户群组信息
        List<Group> groups = userGroupService.getUserGroups(user.getId());

        List<Group> groupList = groups.stream()
                .peek(x -> {

                    List<GroupUser> users = x.getUsers().stream().peek(u -> {
                        User userInfo = ImConfig.userListener().onGetUser(u.getId());
                        BeanUtil.copyProperties(userInfo, u, "role", "black");
                        // 如果是群组, 并且ID不等于当前用户, 并且房间名为空 说明就是对方且没有备注, 那么改名字咯
                        if (x.getIsFriend() && StrUtil.isBlank(x.getRoomName()) && !userInfo.getId().equals(user.getId())) {
                            x.setFriendId(userInfo.getId());
                            x.setAvatar(userInfo.getAvatar());
                            x.setRoomName(userInfo.getUsername());
                        }
                    }).collect(Collectors.toList());

                    x.setUsers(users);
                }).collect(Collectors.toList());

        user.setStatus(Status.online());

        String success = RespBody.success(CommandEnum.COMMAND_LOGIN_RESP, new LoginRespBody(user.getId()));
        Im.bSend(channelContext, WsResponse.fromText(success, ImConfig.CHARSET));

        log.info("登录{}", uid);
        Im.bindUser(channelContext, user, groupList);

        // 回调用户状态变化
        ImConfig.get().getImUserPropListener().onStatusChange(Status.online());

        UserStatusBody build = UserStatusBody.builder()
                .user(BeanUtil.copyProperties(user, GroupUser.class))
                .build();

        for (Group group : groups) {
            // 绑定群组
            Tio.bindGroup(channelContext, group.getRoomId());

            Optional<GroupUser> first = group.getUsers().stream().filter(x -> x.getId().equals(user.getId())).findFirst();
            if(first.isPresent()){
                GroupUser groupUser = first.get();
                build.getUser().setRole(groupUser.getRole());
            }

            build.setRoomId(group.getRoomId());
            Chat.sendToGroup(build, channelContext);
        }

        auth.setLastLoginIp(channelContext.getClientNode().getIp());
        authService.update(auth);

        return null;
    }

}
